import re
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output

from .app import app
from .components import navigation
from .pages import login, register, task_detail, profile, not_found, home
from .api_client import is_user_authenticated


# -----------
# Main Layout
app.layout = html.Div([
    dcc.Location(id='location', refresh=False),
    html.Div([
        navigation.new(app, id='nav-bar'),
        html.Div(id='page-content')
    ]),
    html.Div(id='bin', style={'display': 'none'}),

    # Experiment
    html.Div(id='hehe')
])


# ----------
# App Router
@app.callback(
    Output('page-content', 'children'),
    Input('location', 'pathname'))
def on_location_changed(path):
    # normalize path
    path = path.strip('/')

    is_authenticated = is_user_authenticated()

    # route public views
    if path == 'login':
        if is_authenticated:
            return home.content
        return login.content

    if path == 'register':
        if is_authenticated:
            return home.content
        return register.content

    if path == '':
        if is_authenticated:
            return home.content
        else:
            return login.content

    # guard non public views
    if not is_authenticated:
        return login.content

    if path == 'home':
        return home.content

    if path == 'profile':
        return profile.content

    if re.match(r'^tasks/\d+$', path):
        return task_detail.content

    return not_found.content


# ---------
# Serve App
app.run_server(debug=True, host='0.0.0.0', port=8050)
